﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsPipeClient
{
    public partial class FormClient : Form
    {
        NamedPipeClientStream m_pipe= new NamedPipeClientStream("localhost", "Echo", PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.WriteThrough);
        public FormClient()
        {
            InitializeComponent();

            Task.Run(() => { m_pipe.Connect(); 
                var data = new byte[1000];
                m_pipe.BeginRead(data, 0, data.Length, ReceiveData, data);
            });
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if(m_pipe.IsConnected)
            {
                var text = "haha";
                m_pipe.BeginWrite(Encoding.UTF8.GetBytes(text), 0, text.Length, null, null);
              
            }
        }

        private void ReceiveData(IAsyncResult ar)
        {
            int bytesRead = m_pipe.EndRead(ar);
            byte[] data = (byte[])ar.AsyncState;
            string message = Encoding.UTF8.GetString(data, 0, bytesRead);
            BeginInvoke(new Action(() => textBox1.Text = message));
            var recvData = new byte[1000];
            m_pipe.BeginRead(recvData, 0, recvData.Length, ReceiveData, recvData);
        }
    }
    
}
